/**
 * 柯里化工具函数
 * @param {Function} fn 被柯里化函数
 * @param {Array} holes 用于递归 存储占位符的索引
 * @returns 柯里化后的函数
 */
function curry (fn, holes = []) {
  var slice = Array.prototype.slice
  var args = slice.call(arguments, 2)
  var fnLen = fn.length
  return function () {
    var _args = args.slice()
    var i
    var index = 0
    for (i = 0; i < arguments.length; i++) {
      var arg = arguments[i]
      if (arg === '_') {
        _args.push(arg)
        holes.push(_args.length - 1)
        index++
      } else {
        if (holes.length && _args[holes[index]] === '_') {
          _args.splice(holes[index], 1, arg)
          holes.splice(index, 1)
        } else {
          _args.push(arg)
        }
      }
    }
    if (_args.length < fnLen || holes.length) {
      return curry.call(this, fn, holes, ..._args)
    } else {
      return fn.apply(this, _args)
    }
  }
}

export default curry